<template>
  <Editor :id="props.id" v-model="content" :init="init" :disabled="props.disabled" />
  <div class="tinymce-btn">
    <template v-if="props.hasBtn">
      <el-button @click="tinymceClose">清空</el-button>
      <el-button type="primary" @click="tinymceSave">确定</el-button>
    </template>
  </div>
</template>

<script setup lang="ts">
import { computed } from "vue"
import Editor from "@tinymce/tinymce-vue"
import "tinymce/tinymce"
import "tinymce/icons/default/icons"
import "tinymce/themes/silver"
// import "tinymce/models/dom/model"
//按需引入插件
import "tinymce/plugins/image"
import "tinymce/plugins/table"
import "tinymce/plugins/lists"
import "tinymce/plugins/link"
import "tinymce/plugins/wordcount"
import "tinymce/plugins/code"
import "tinymce/plugins/preview"
import "tinymce/plugins/fullscreen"
import "tinymce/plugins/save" //保存
import type { IEditorProps } from "./type"
import { uploadImageInCommunity } from "@/service/file/uploadFile"
import { InnerConfirm, messageReminder } from "@/utils/notificationHint"

const props = withDefaults(defineProps<IEditorProps>(), {
  id: "",
  editorHeight: 500,
  hasBtn: true,
  modelValue: "",
  disabled: false,
  maxSize: 10 * 1024 * 1024,
  accept: "image/jpeg, image/png, image/jpg,image/webp"
})

const emits = defineEmits(["update:modelValue", "handleBtnClick"])
// content收集的文本内容
const content = computed({
  get: () => props.modelValue, // 获取是通过v-model绑定的的数据获取
  set: (val) => {
    emits("update:modelValue", val) //设置是通过v-model监听的事件进行更新
  }
})

const image_upload_handler = async (blobInfo, success, failure) => {
  const maxSize = 1
  const blob = blobInfo.blob()

  // 判断图片大小
  if (blob.size / 1024 / 1024 > maxSize) {
    failure("图片大小不能超过" + maxSize + "MB")
    return
  }

  // 创建一个FormData对象，用于封装表单数据
  const formData = new FormData()
  formData.append("singleFile", blob, blobInfo.filename)

  let result = await uploadImageInCommunity(formData)
  console.log("lllllll", result)
  if (result.data.code == 200) {
    console.log("上传成功")
    success(result.data.data)
  } else {
    console.log("上传失败")
    // 上传失败，调用failure回调函数
    failure("上传图片失败，请重试。")
  }
}

const init = {
  selector: `#${props.id}`,
  promotion: false,
  help_accessibility: false,
  branding: false,
  language_url: "/tinymce/langs/zh_CN.js", //引入语言包文件
  language: "zh_CN", //语言类型
  codesample_global_prismjs: true,
  plugins: "image table lists link wordcount code preview fullscreen",
  editimage_cors_hosts: ["picsum.photos"],
  menubar: "file edit view insert format tools table help",
  toolbar:
    "undo redo | accordion accordionremove | blocks  fontsize | bold italic underline strikethrough | align numlist bullist | link image | table media | lineheight outdent indent| forecolor backcolor removeformat | charmap emoticons | code fullscreen preview",
  auto_focus: true, //自动获取焦点
  placeholder: "请输入内容", //
  image_advtab: true,
  // images_upload_url: props.url,
  images_upload_handler: image_upload_handler,
  save_oncancelcallback: () => {
    console.log("Save canceled")
  },
  save_onsavecallback: () => {
    console.log("Saved")
  },
  content_filter: (args) => {
    args.content = args.content.replace(/<script[^>]*>([\S\s]*?)<\/script>/gi, "")
  },
  paste_preprocess: function (plugin, args) {
    // console.log(args.content);

    // eg.将所有粘贴进来的内容中的 <script> 标签过滤掉
    args.content = args.content.replace(/<script[^>]*>([\S\s]*?)<\/script>/gi, "")
  },
  importcss_append: true,
  // file_picker_callback: false,
  height: props.editorHeight,
  image_caption: true,
  quickbars_selection_toolbar: "bold italic | quicklink h2 h3 blockquote quickimage quicktable",
  noneditable_class: "mceNonEditable",
  toolbar_mode: "sliding",
  contextmenu: "link image table",
  // skin: 'oxide',
  // content_css: 'default',
  skin_url: "/tinymce/skins/ui/oxide", // 手动引入CSS
  content_css: "/tinymce/skins/content/default/content.css", // 手动引入CSS
  content_style: "body { font-family:Helvetica,Arial,sans-serif; font-size:16px }"
}

// 清空富文本框
function tinymceClose() {
  // 清空编辑的内容
  content.value = ""
  messageReminder({
    message: "删除成功！",
    type: "success"
  })
}

// 点击确认按钮
function tinymceSave() {
  // 触发自定义事件
  emits("handleBtnClick")
}
</script>

<style lang="less" scoped>
.tinymce-btn {
  height: 46px;
  margin: 20px 0px 0px 0px;
  .el-button {
    float: right;
    margin-left: 10px;
  }
}
</style>
